import { ArgumentsHost, Catch, ExceptionFilter, HttpException, HttpStatus } from '@nestjs/common'
import winstonLogger from '../common/logger/winston.config';

@Catch()
export class AllExceptionFilter implements ExceptionFilter {

	catch(exception: any, host: ArgumentsHost) {
		const context = host.switchToHttp()
		const response = context.getResponse<IResponse>()
		const request = context.getRequest<IRequest>()
		const isHttpError = exception instanceof HttpException
		const status = isHttpError ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;
		const message = isHttpError ? exception.getResponse() : exception.message

		// 获取请求参数
		const { method, url, ip } = request;
		const queryParams = request.query;
		const bodyParams = request.body;
		const params = request.params;

		// 获取 user 和 trackId
		const user = request.user ? JSON.stringify(request.user) : 'Not authenticated';
		const trackId = request.trackId || 'No trackId';
		const userAgent = request.headers['user-agent'] || '';

		// 构建错误日志消息
		const errorLog = `
			Request: ${method} ${url}
			Status: ${status}
			User Agent: ${userAgent}
			IP: ${ip}
			Query Params: ${JSON.stringify(queryParams)}
			Body Params: ${JSON.stringify(bodyParams)}
			Route Params: ${JSON.stringify(params)}
			User: ${user}
			TrackId: ${trackId}
				`.trim();

		// 使用 Winston 记录错误日志
		winstonLogger.error(errorLog, { service: 'ExceptionFilter' });

		console.error("错误：", exception)
		if(isHttpError){
			response.status(status).send(message)
		} else {
			response.status(status).send({
				statusCode: status,
				message: message
			})
		}
	}
}
